﻿using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	public class ConnectPipeManage
	{
		public string GetFamilySymbolName(ConnectPipeStyle pipeStyle)
		{
			string result = "";
			switch (pipeStyle)
			{
			case ConnectPipeStyle.Elbow:
				result = "水管弯头";
				break;
			case ConnectPipeStyle.Tee:
				result = "Y型三通";
				break;
			case ConnectPipeStyle.Cross:
				result = "水管四通";
				break;
			case ConnectPipeStyle.Reduce:
				result = "水管变径";
				break;
			case ConnectPipeStyle.Back:
				result = "水管弯头";
				break;
			}
			return result;
		}

		public FamilySymbol GetFamilySymbolByName(string fsName, Autodesk.Revit.DB.Document doc, ref string loadMSG)
		{
			FamilySymbol familySymbol = null;
			if (string.IsNullOrEmpty(fsName))
			{
				loadMSG = "族名不能为空！";
				return familySymbol;
			}
			familySymbol = YJKRevitTools.GetFamilySymbol(fsName, doc);
			if (familySymbol == null)
			{
				string text = Path.Combine(Product.FamilyLocation, RevitVersion.Version, "Fitting", fsName + ".rfa");
				if (!File.Exists(text))
				{
					loadMSG = "族不存在或者加载地址不正确！";
					return familySymbol;
				}
				SubTransaction subTransaction = new SubTransaction(doc);
				subTransaction.Start();
				Family family = null;
				doc.LoadFamily(text, out family);
				if (family == null)
				{
					subTransaction.RollBack();
					return null;
				}
				familySymbol = YJKRevitTools.GetFamilySymbol(fsName, doc);
				subTransaction.Commit();
			}
			return familySymbol;
		}

		public string SetPipeReduceFitting(IList<Pipe> pipes)
		{
			string result = "";
			if (pipes == null || pipes.Count <= 0)
			{
				return "缺少水管.";
			}
			Document document = pipes[0].Document;
			string familySymbolName = this.GetFamilySymbolName(ConnectPipeStyle.Reduce);
			if (string.IsNullOrEmpty(familySymbolName))
			{
				return "没有找到变径族。";
			}
			FamilySymbol familySymbolByName = this.GetFamilySymbolByName(familySymbolName, document, ref result);
			if (familySymbolByName == null)
			{
				return result;
			}
			foreach (Pipe piping in pipes)
			{
				new YJKPiping<Pipe>(piping).ChangeFirstTransition(familySymbolByName);
			}
			return result;
		}

		public string SetPipeElbowFitting(IList<Pipe> pipes, string elbowName)
		{
			string result = "";
			if (pipes == null || pipes.Count <= 0)
			{
				return "缺少水管.";
			}
			Document document = pipes[0].Document;
			if (string.IsNullOrEmpty(elbowName))
			{
				return "没有找到变径族。";
			}
			FamilySymbol familySymbolByName = this.GetFamilySymbolByName(elbowName, document, ref result);
			if (familySymbolByName == null)
			{
				return result;
			}
			foreach (Pipe piping in pipes)
			{
				new YJKPiping<Pipe>(piping).ChangeFirstElbow(familySymbolByName);
			}
			return result;
		}
	}
}
